package com.atilim.cargo.util;

import java.text.SimpleDateFormat;
import java.util.List;

import org.json.JSONObject;

import com.atilim.cargo.model.Vertex;


public class Utility {

	/**
	 * km 
	 * @param first
	 * @param second
	 * @return
	 */
	public static double distance (Vertex first, Vertex second) {
		if (first == null || second == null)
			return 0.0;
		return distance(Double.parseDouble(first.getLat()), Double.parseDouble(first.getLon()), 
				Double.parseDouble(second.getLat()), Double.parseDouble(second.getLon()), 'K');
	}
	
	public static double distanceOfPath (List<Vertex> path) {
		
		double distance = 0.0;
		Vertex destination = null, target = null;
		for (int i=0;i<path.size();i++) {
			if (i + 1 < path.size()) {
				target = path.get(i);
				destination = path.get(i + 1);
				distance += Utility.distance(destination, target);				
			}
		}
		return distance;
	}
	
	public static double distance(double lat1, double lon1, double lat2, double lon2,
			char unit) {
		double theta = lon1 - lon2;
		double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
				+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
				* Math.cos(deg2rad(theta));
		dist = Math.acos(dist);
		dist = rad2deg(dist);
		dist = dist * 60 * 1.1515;
		if (unit == 'K') {
			dist = dist * 1.609344;
		} else if (unit == 'N') {
			dist = dist * 0.8684;
		}
		return (dist);
	}

	/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
	/* :: This function converts decimal degrees to radians : */
	/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
	private static double deg2rad(double deg) {
		return (deg * Math.PI / 180.0);
	}

	/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
	/* :: This function converts radians to decimal degrees : */
	/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */
	private static double rad2deg(double rad) {
		return (rad * 180.0 / Math.PI);
	}
	
	/**
	 * 
	 * @param v1 yolun birinci noktası
	 * @param v2 yolun ikinci noktası
	 * @param xp noktanın lat'ı
	 * @param yp noktanın lng'si
	 * @return
	 */
	public static Vertex findNearestPointRoadToPoint (Vertex v1, Vertex v2, double xp, double yp) {
		double x1 = Double.parseDouble(v1.getLat());
		double y1 = Double.parseDouble(v1.getLon());
		double x2 = Double.parseDouble(v2.getLat());
		double y2 = Double.parseDouble(v2.getLon());
		
		double m = (y2 - y1) / (x2 - x1);
		double b = y2 - (m * x2);
		
		//y = m * x + b;
		
		double x0 = ( (m * yp) + xp - (m * b) ) / ( m * m + 1 );
		double y0 = m * ( ( (m * yp) + xp - (m * b) ) / (m * m + 1) ) + b;
		
		return new Vertex("nearest", Double.toString(x0), Double.toString(y0));
		
	}
}
